'use strict';
const db = uniCloud.database();
const collection = db.collection('user_saige_data');

// 统一响应格式
const response = (code, data, message) => {
	return {
		code,
		data,
		message
	};
};

exports.main = async (event, context) => {
	const {
		action,
		params
	} = event;

	try {
		switch (action) {
			case 'add':
				return await addRecord(params);
			case 'batchAdd':
				return await batchAddRecords(params);
			case 'get':
				return await getRecords(params);
			case 'update':
				return await updateRecord(params);
			case 'delete':
				return await deleteRecord(params);
			case 'search':
				return await searchRecords(params);
			default:
				return response(400, null, '无效的操作类型');
		}
	} catch (e) {
		console.error('云函数错误:', e);
		return response(500, null, `服务器错误: ${e.message}`);
	}
};

// 添加新记录
async function addRecord(data) {
	if (!data.foot_ring_number_a || !data.foot_ring_number_b) {
		return response(400, null, '足环号不能为空');
	}

	// 自动生成序号（获取当前最大序号+1）
	const maxSerial = await collection.orderBy('serial_number', 'desc').limit(1).get();
	const nextSerial = maxSerial.data.length > 0 ? maxSerial.data[0].serial_number + 1 : 1;

	const record = {
		...data,
		serial_number: nextSerial,
		create_time: new Date().toLocaleString('zh-CN', {
			year: 'numeric',
			month: '2-digit',
			day: '2-digit',
			hour: '2-digit',
			minute: '2-digit',
			second: '2-digit',
			hour12: false
		}),
		update_time: new Date().toLocaleString('zh-CN', {
			year: 'numeric',
			month: '2-digit',
			day: '2-digit',
			hour: '2-digit',
			minute: '2-digit',
			second: '2-digit',
			hour12: false
		})
	};

	const res = await collection.add(record);
	return response(200, {
		id: res.id
	}, '添加成功');
}

// 获取记录（分页查询）
async function getRecords({
	page = 1,
	pageSize = 20
}) {
	const countResult = await collection.count();
	const total = countResult.total;

	const res = await collection
		.orderBy('serial_number', 'asc')
		.skip((page - 1) * pageSize)
		.limit(pageSize)
		.get();

	return response(200, {
		data: res.data,
		total,
		page,
		pageSize
	}, '查询成功');
}

// 更新记录
async function updateRecord({
	id,
	updateData
}) {
	if (!id) return response(400, null, '记录ID不能为空');

	const updateRes = await collection.doc(id).update({
		...updateData,
		update_time: Date.now()
	});

	if (updateRes.updated === 0) {
		return response(404, null, '未找到指定记录');
	}

	return response(200, null, '更新成功');
}

// 删除记录
async function deleteRecord({
	id
}) {
	if (!id) return response(400, null, '记录ID不能为空');

	const deleteRes = await collection.doc(id).remove();

	if (deleteRes.deleted === 0) {
		return response(404, null, '未找到指定记录');
	}

	return response(200, null, '删除成功');
}

// 高级搜索
async function searchRecords(params) {
	const {
		keyword,
		owner,
		footRing,
		page = 1,
		pageSize = 20
	} = params;
	const query = {};

	// 关键词搜索（鸽主或指定人）
	if (keyword) {
		query.$or = [{
				owner_a: new RegExp(keyword, 'i')
			},
			{
				owner_b: new RegExp(keyword, 'i')
			},
			{
				designated_person: new RegExp(keyword, 'i')
			}
		];
	}

	// 鸽主过滤
	if (owner) {
		query.$or = [{
				owner_a: owner
			},
			{
				owner_b: owner
			}
		];
	}

	// 足环号过滤
	if (footRing) {
		query.$or = [{
				foot_ring_number_a: footRing
			},
			{
				foot_ring_number_b: footRing
			}
		];
	}

	const countResult = await collection.where(query).count();
	const total = countResult.total;

	const res = await collection
		.where(query)
		.orderBy('serial_number', 'asc')
		.skip((page - 1) * pageSize)
		.limit(pageSize)
		.get();

	return response(200, {
		data: res.data,
		total,
		page,
		pageSize
	}, '搜索成功');
}

// 批量添加记录
async function batchAddRecords(records) {
	if (!Array.isArray(records) || records.length === 0) {
		return response(400, null, '记录列表不能为空');
	}

	// 检查足环号唯一性 - 确保两个足环号同时存在
	const existingRecords = await Promise.all(records.map(async record => {
		const result = await collection.where({
			$or: [
				{
					foot_ring_number_a: record.foot_ring_number_a,
					foot_ring_number_b: record.foot_ring_number_b
				},
				{
					foot_ring_number_a: record.foot_ring_number_b,
					foot_ring_number_b: record.foot_ring_number_a
				}
			]
		}).get();
		return result.data.length > 0 ? record : null;
	}));

	const duplicatePairs = existingRecords.filter(Boolean);
	if (duplicatePairs.length > 0) {
		const duplicateNumbers = duplicatePairs.map(pair => 
			`${pair.foot_ring_number_a}-${pair.foot_ring_number_b}`
		);
		return response(400, {
			duplicatePairs
		}, `指定配对已存在: ${duplicateNumbers.join(', ')}`);
	}

	// 获取当前最大序号
	const maxSerial = await collection.orderBy('serial_number', 'desc').limit(1).get();
	let nextSerial = maxSerial.data.length > 0 ? maxSerial.data[0].serial_number + 1 : 1;

	// 为每条记录添加序号和时间戳
	const recordsToAdd = records.map(record => {
		if (!record.foot_ring_number_a || !record.foot_ring_number_b) {
			throw new Error('足环号不能为空');
		}

		return {
			...record,
			serial_number: nextSerial++,
			create_time: Date.now(),
			update_time: Date.now()
		};
	});

	// 批量插入
	const res = await collection.add(recordsToAdd);
	return response(200, {
		insertedCount: res.inserted
	}, '批量添加成功');
}